//1.双指针-三数之和
class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> ret;
        int n = nums.size(); 
        sort(nums.begin(), nums.end());
        for(int i = 0; i < n; )
        {
            int t = -nums[i];
            if(t < 0) break; //小优化
            int l = i + 1, r = n - 1;
            while(l < r)
            {
                if(nums[l] + nums[r] > t) r--;
                else if(nums[l] + nums[r] < t) l++;
                else 
                {
                    ret.push_back({nums[i], nums[l], nums[r]});
                    l++, r--;
                    while(l < r && nums[l - 1] == nums[l]) l++;
                    while(l < r && nums[r + 1] == nums[r]) r--;
                }
            }
            i++;
            while(i < n && nums[i] == nums[i - 1]) i++;
        }
        return ret;
    }
};


//2.双指针-四数之和
class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        int n = nums.size();
        vector<vector<int>> ret;
        sort(nums.begin(), nums.end());
        for(int i = 0; i < n;)
        {
            for(int j = i + 1; j < n;)
            {
                long long t = (long long)target - nums[i] - nums[j];
                int l = j + 1, r = n - 1;
                while(l < r)
                {
                    if(nums[l] + nums[r] > t) r--;
                    else if(nums[l] + nums[r] < t) l++;
                    else 
                    {
                        ret.push_back({nums[i], nums[j], nums[l], nums[r]});
                        l++, r--;
                        while(l < r && nums[l] == nums[l - 1]) l++;
                        while(l < r && nums[r] == nums[r + 1]) r--;
                    }
                }
                j++;
                while(j < n && nums[j] == nums[j - 1]) j++;
            }
            i++;
            while(i < n && nums[i] == nums[i - 1]) i++; 
        }
        return ret;
    }
};